package tech.aistar.corejava.day09.clone;

/**
 * @Author:         lya
 * @Description:   本类的作用描述:深拷贝 --  浅拷贝
 * @param
 * @return:
 * @CreateDate:    2019/7/25 20:02
 * @Version:       1.0
*/
public class User implements Cloneable{
    private int id;

    private String name;

    private UserInfo userInfo;

    public User() {
    }

    public User(int id, String name, UserInfo userInfo) {
        this.id = id;
        this.name = name;
        this.userInfo = userInfo;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public UserInfo getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("User{");
        sb.append("id=").append(id);
        sb.append(", name='").append(name).append('\'');
        sb.append(", userInfo=").append(userInfo);
        sb.append('}');
        return sb.toString();
    }

    /**
     * 浅拷贝
     * @return
     * @throws CloneNotSupportedException
     */
//    @Override
//    protected Object clone() throws CloneNotSupportedException{
//        return super.clone();
//    }

    /**
     * 深拷贝
     * @return
     * @throws CloneNotSupportedException
     */
    @Override
    protected Object clone() throws CloneNotSupportedException {
        //原来的对象和副本之间应该脱离关系了
        User user = new User();
        //将原来对象的所有的属性的值全部设置到这个新的对象user中

        //User u = new User(1,"tom",new UserInfo(1,"110"));
        //User copy = (User)u.clone();
        user.setId(this.id);
        user.setName(this.name);

        //判断
        if(this.userInfo != null ){
            UserInfo info = new UserInfo();

            //需要对userInfo里面的所有的数据进行一一赋值
            info.setId(this.userInfo.getId());
            info.setPhone(this.userInfo.getPhone());

            user.setUserInfo(info);
        }
    return user;
    }
}
